import { Request, Response, NextFunction } from 'express';
import Joi from 'joi';

// 创建教案验证规则
const createLessonPlanSchema = Joi.object({
  title: Joi.string().required().trim().max(200).messages({
    'string.empty': '教案标题不能为空',
    'string.max': '教案标题不能超过200个字符',
    'any.required': '教案标题是必填项'
  }),
  content: Joi.string().required().messages({
    'string.empty': '教案内容不能为空',
    'any.required': '教案内容是必填项'
  }),
  subject: Joi.string().required().trim().messages({
    'string.empty': '学科不能为空',
    'any.required': '学科是必填项'
  }),
  grade: Joi.string().required().trim().messages({
    'string.empty': '年级不能为空',
    'any.required': '年级是必填项'
  }),
  courseType: Joi.string().required().trim().messages({
    'string.empty': '课程类型不能为空',
    'any.required': '课程类型是必填项'
  }),
  tags: Joi.array().items(Joi.string().trim()).default([]),
  attachments: Joi.array().items(Joi.string().allow('')).default([]),
  isPublic: Joi.boolean().default(true),
  status: Joi.string().valid('draft', 'published', 'archived').default('draft')
});

// 草稿验证规则 (更宽松的验证)
const draftLessonPlanSchema = Joi.object({
  title: Joi.string().trim().max(200).default('未命名教案').messages({
    'string.max': '教案标题不能超过200个字符'
  }),
  content: Joi.string().default(''),
  subject: Joi.string().trim().default(''),
  grade: Joi.string().trim().default(''),
  courseType: Joi.string().trim().default(''),
  tags: Joi.array().items(Joi.string().trim()).default([]),
  attachments: Joi.array().items(Joi.string().allow('')).default([]),
  isPublic: Joi.boolean().default(true),
  status: Joi.string().valid('draft').default('draft')
});

// 更新教案验证规则
const updateLessonPlanSchema = Joi.object({
  title: Joi.string().trim().max(200).messages({
    'string.max': '教案标题不能超过200个字符'
  }),
  content: Joi.string(),
  subject: Joi.string().trim(),
  grade: Joi.string().trim(),
  courseType: Joi.string().trim(),
  tags: Joi.array().items(Joi.string().trim()),
  attachments: Joi.array().items(Joi.string().allow('')),
  isPublic: Joi.boolean(),
  status: Joi.string().valid('draft', 'published', 'archived')
});

// 搜索教案验证规则
const searchLessonPlanSchema = Joi.object({
  q: Joi.string().trim().allow('').optional().messages({
    'string.empty': '搜索关键词不能为空'
  }),
  subject: Joi.string().trim().allow('').optional(),
  grade: Joi.string().trim().allow('').optional(),
  courseType: Joi.string().trim().allow('').optional(),
  tags: Joi.string().trim().allow('').optional(),
  author: Joi.string().trim().allow('').optional(),
  status: Joi.string().valid('draft', 'published', 'archived').optional(),
  sortBy: Joi.string().valid('relevance', 'date', 'views', 'likes').default('relevance'),
  page: Joi.number().integer().min(1).default(1),
  limit: Joi.number().integer().min(1).max(100).default(10)
});

// 查询教案列表验证规则
const getListSchema = Joi.object({
  subject: Joi.string().trim().allow('').optional(),
  grade: Joi.string().trim().allow('').optional(),
  courseType: Joi.string().trim().allow('').optional(),
  status: Joi.string().valid('draft', 'published', 'archived', '').allow('').optional(),
  sortBy: Joi.string().valid('relevance', 'date', 'views', 'likes').default('date'),
  page: Joi.number().integer().min(1).default(1),
  limit: Joi.number().integer().min(1).max(100).default(10)
});

// 创建教案验证中间件
export const validateCreateLessonPlan = (req: Request, res: Response, next: NextFunction): void => {
  const { error, value } = createLessonPlanSchema.validate(req.body);
  
  if (error) {
    res.status(400).json({
      success: false,
      message: '输入验证失败',
      errors: error.details.map(detail => ({
        field: detail.path.join('.'),
        message: detail.message
      }))
    });
    return;
  }
  
  req.body = value;
  next();
};

// 草稿验证中间件
export const validateDraftLessonPlan = (req: Request, res: Response, next: NextFunction): void => {
  const { error, value } = draftLessonPlanSchema.validate(req.body);
  
  if (error) {
    res.status(400).json({
      success: false,
      message: '输入验证失败',
      errors: error.details.map(detail => ({
        field: detail.path.join('.'),
        message: detail.message
      }))
    });
    return;
  }
  
  req.body = value;
  next();
};

// 更新教案验证中间件
export const validateUpdateLessonPlan = (req: Request, res: Response, next: NextFunction): void => {
  const { error, value } = updateLessonPlanSchema.validate(req.body);
  
  if (error) {
    res.status(400).json({
      success: false,
      message: '输入验证失败',
      errors: error.details.map(detail => ({
        field: detail.path.join('.'),
        message: detail.message
      }))
    });
    return;
  }
  
  req.body = value;
  next();
};

// 搜索教案验证中间件
export const validateSearchLessonPlan = (req: Request, res: Response, next: NextFunction): void => {
  const { error, value } = searchLessonPlanSchema.validate(req.query);
  
  if (error) {
    res.status(400).json({
      success: false,
      message: '搜索参数验证失败',
      errors: error.details.map(detail => ({
        field: detail.path.join('.'),
        message: detail.message
      }))
    });
    return;
  }
  
  req.query = value;
  next();
};

// 查询教案列表验证中间件
export const validateGetLessonPlanList = (req: Request, res: Response, next: NextFunction): void => {
  const { error, value } = getListSchema.validate(req.query);
  
  if (error) {
    res.status(400).json({
      success: false,
      message: '查询参数验证失败',
      errors: error.details.map(detail => ({
        field: detail.path.join('.'),
        message: detail.message
      }))
    });
    return;
  }
  
  req.query = value;
  next();
};

// ObjectId验证中间件
export const validateObjectId = (req: Request, res: Response, next: NextFunction): void => {
  const { id } = req.params;
  
  if (!id || !/^[0-9a-fA-F]{24}$/.test(id)) {
    res.status(400).json({
      success: false,
      message: '无效的教案ID格式'
    });
    return;
  }
  
  next();
};